package com.glory.brepda.activity.mfg;


import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.PickingDataAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.PickingEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.MyUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

public class PickingApplyActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpID)
    FreeUI_ClearEditText etEqpID;
    @BindView(R.id.rvPickingList)
    RecyclerView rvPickingList;
    @BindView(R.id.flTypeList)
    FrameLayout flTypeList;
    @BindView(R.id.tvType)
    TextView tvType;
    @BindView(R.id.ivType)
    ImageView ivType;
    @BindView(R.id.flSpecList)
    FrameLayout flSpecList;
    @BindView(R.id.tvSpec)
    TextView tvSpec;
    @BindView(R.id.ivSpec)
    ImageView ivSpec;
    @BindView(R.id.tvStep)
    TextView tvStep;
    @BindView(R.id.tvStepDesc)
    TextView tvStepDesc;
    @BindView(R.id.tvDeleteData)
    TextView tvDeleteData;
    @BindView(R.id.tvAddData)
    TextView tvAddData;
    @BindView(R.id.tvEqpLocation)
    TextView tvEqpLocation;
    @BindView(R.id.tvpartName)
    TextView tvpartName;
    @BindView(R.id.tvpartDesc)
    TextView tvpartDesc;
    @BindView(R.id.etQty)
    FreeUI_ClearEditText etQty;

    // 针对胶水是否需要分支
    CheckBox cbGlueNeedBranch;

    private PickingDataAdapter mPickingDataAdapter;
    private final ArrayList<String> typeList = new ArrayList<>();
    private final ArrayList<String> specList = new ArrayList<>();
    private FreeUI_GeneralPop mTypePop;
    private FreeUI_GeneralPop mSpecPop;
    private String type = "";
    // 字典存储形式：物料规格：厂家信息
    private HashMap<String, String> materialMap;
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pickingapply;
    }

    @Override
    protected void initView() {
        tvTitle.setText("领料申请");
        setMainLayout(llMain);

        mPickingDataAdapter = new PickingDataAdapter(null);
        mPickingDataAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mPickingDataAdapter.isFirstOnly(true);
        initRecyclerView(rvPickingList, this);
        rvPickingList.setAdapter(mPickingDataAdapter);

        // 胶水是否需要分支选择框
        cbGlueNeedBranch = findViewById(R.id.cbGlueNeedBranch);
    }

    @Override
    protected void initData() {
        initEdit(etLot, s -> {
            getPickingData("QUERYLOTINFO");
        });
        initEdit(etEqpID, s -> {
            getPickingData("QUERYEQPINFO");
        });
    }

    private void getPickingData(String actiontype) {
        FreeUI_EntityCallBack<BaseResponseBean<PickingEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<PickingEntity>>
                (new TypeToken<BaseResponseBean<PickingEntity>>() {
                }.getType(),getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<PickingEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(PickingApplyActivity.this, false, getSupportFragmentManager())) {
                    switch (actiontype) {
                        case "QUERYLOTINFO":
                            tvStep.setText(response.body().getResponse().getBody().getSTEPNAME());
                            tvStepDesc.setText(response.body().getResponse().getBody().getSTEPDESC());
                            tvpartName.setText(response.body().getResponse().getBody().getPARTNAME());
                            tvpartDesc.setText(response.body().getResponse().getBody().getPARTDESC());

                            // bug：重复扫批次时，列表如果还有值的话会重复添加，造成冗余
                            // 解决，接口返回值时，如果列表有值的话，执行清空逻辑
                            if (!typeList.isEmpty()) {
                                typeList.clear();
                            }

                            // 清空一下规格里面的数据，避免脏数据或者用户对系统逻辑有歧义
                            if (!specList.isEmpty()) {
                                specList.clear();
                            }

                            for (PickingEntity.Aduref data : response.body().getResponse().getBody().getADUREFLIST()) {
                                typeList.add(data.getKEYID() + "/" + data.getTEXT());
                            }
                            // 请求成功后清空一下领料类型和规格的信息，防止提交错误信息（脏数据）
                            MyUtils.clearTextInTextView(tvType, tvSpec);
                            break;
                        case "QUERYEQPINFO":
                            tvEqpLocation.setText(response.body().getResponse().getBody().getEQPLOCATION());
                            break;
                        case "QUERYMATSPEC":
                            // 修复： 点击物料规格之后，如果原来列表已经有值了，会继续添加上去，造成数据重复
                            // 如果请求过后，假设列表已经有值了，直接清空一下列表
                            if (specList.size() > 0) {
                                specList.clear();
                            }

                            // 解析工单BOMLINE的材料规格以及指定的厂家【后续主要起到提示的作用】
                            parseBomLineSpecAndManufacture(response.body().getResponse().getBody().getMATERIALSPECLIST());
                            if (materialMap != null && !materialMap.isEmpty()) {
                                specList.addAll(new ArrayList<>(materialMap.keySet()));
                                tvSpec.setText(specList.get(0));
                            } else {
                                // 假设请求回来的物料列表为空，就需要清空上一下选择的信息，这里直接给它清空掉
                                MyUtils.clearTextInTextView(tvSpec);
                            }
                            break;
                        case "APPOINTMENT":
                            showToast("提交成功",true);
                            MyUtils.clearDataInAdapter(mPickingDataAdapter);
                            break;
                    }

                } else {
                    // MES 接口返回有错误，则根据请求类型 清空掉一些文本框的信息
                    clearListAndTextViewWhenError(actiontype);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<PickingEntity>> response) {
                super.onError(response);
                FreeApi_LogUtils.saveErrorMessages(response.getException(), "PICKAPPOINTMENT");
                // 解决网络问题，及时清理掉一些脏数据问题，避免提交错误的信息
                if (response.getException() instanceof java.net.SocketException) {
                    clearListAndTextViewWhenError(actiontype);
                }
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", actiontype);
        switch (actiontype){
            case "QUERYLOTINFO":
                map.addProperty("LOTID", getText(etLot));
                break;
            case "QUERYEQPINFO":
                map.addProperty("EQUIPMENTID", getText(etEqpID));
                break;
            case "QUERYMATSPEC":
                map.addProperty("LOTID", getText(etLot));
                map.addProperty("MATERIALTYPE", type);
                break;
            case "APPOINTMENT":
                map.add("APPOINTMENTTOOLLIST", new JsonParser().parse(new Gson().toJson(mPickingDataAdapter.getData())).getAsJsonArray());
                break;
        }

        NetUtils.requestPostNet("IF.PICKAPPOINTMENT", "Common", PickingApplyActivity.this, map, callBack);

    }

    /**
     * 解析物料规格，及其包含的厂家信息，后续提交领料单时，如果有长啊及信息，则将厂家信息也传过去
     * @param materialSpecList 物料规格及厂家信息（厂家信息不一定会有）列表
     */
    private void parseBomLineSpecAndManufacture(ArrayList<String> materialSpecList) {

        // 清空之前存储的信息
        if (materialMap != null && !materialMap.isEmpty()) {
            materialMap.clear();
        }

        if(materialSpecList == null || materialSpecList.size() == 0) {
            return;
        }

        // 懒加载字典
        if (materialMap == null) {
            materialMap = new HashMap<>(materialSpecList.size());
        }

        // 遍历列表，解析各个规格是否有包含厂家信息，如果有，添加进去字典里面
        for (String materialSpec : materialSpecList) {
            String[] specAndManufacture = StringUtils.split(materialSpec, "||");

            if (specAndManufacture.length == 2) {
                materialMap.put(specAndManufacture[0], specAndManufacture[1]);
                continue;
            }
            materialMap.put(specAndManufacture[0], StringUtils.EMPTY);
        }
    }

    @OnClick({R.id.tvBaseSubmit,R.id.flTypeList,R.id.flSpecList,R.id.tvAddData,R.id.tvDeleteData})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                if (checkPageViewHasEmptyValue()){
                    showToast("填写未完成，请填写相关数据",false);
                    return;
                }
                getPickingData("APPOINTMENT");
                break;
            case R.id.flTypeList:
                if (mTypePop != null) {
                    if (mTypePop.isShowing()) {
                        mTypePop.dismiss();
                    }
                } else {
                    mTypePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flTypeList.getWidth(), typeList, ivType, (codeS, i) -> {
                        tvType.setText(codeS.split("/")[1]);
                        type = codeS.split("/")[0];
                        getPickingData("QUERYMATSPEC");
                        // 24/12/24 新增根据物料类型，显现相关多选框
                        showCheckBoxView();
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivType);
                mTypePop.showAsDropDown(flTypeList, 0, 0);
                break;
            case R.id.flSpecList:
                if (mSpecPop != null) {
                    if (mSpecPop.isShowing()) {
                        mSpecPop.dismiss();
                    }
                } else {
                    mSpecPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flSpecList.getWidth(), specList, ivSpec, (codeS, i) -> {
                        tvSpec.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivSpec);
                mSpecPop.showAsDropDown(flSpecList, 0, 0);
                break;
            case R.id.tvAddData:

                addPickingEntityToAdapter();
                break;

            case R.id.tvDeleteData:
                if (mPickingDataAdapter.getData().size() == 0){
                    showToast("暂未添加数据",false);
                    return;
                }
                mPickingDataAdapter.remove(0);
                break;
        }
    }

    //  根据要求显示一系列的勾选框，目前这里会显示胶水是否需要进行分支
    private void showCheckBoxView() {
        if (StringUtils.equals("Silver_Glue", type) || StringUtils.equals("Insulated", type)
            || StringUtils.equals(type, "Solder") || StringUtils.equals(type, "Solder_Paste")) {
            cbGlueNeedBranch.setVisibility(View.VISIBLE);
            return;
        }
        cbGlueNeedBranch.setVisibility(View.GONE);
    }

    /**
     * 当有请求错误的时候，及时清理掉一些前面留下的信息，防止对本次业务产生影响
     * @param actionType 请求类型
     */
    private void clearListAndTextViewWhenError(String actionType) {
        switch (actionType) {
            // 扫描批次信息出问题时，先清空所有物料相关信息（领料类型、规格）
            case "QUERYLOTINFO":
                // 清空领料类型和规格中的列表
                if (!typeList.isEmpty()) { typeList.clear(); }

                if ( !specList.isEmpty() ) { specList.clear(); }
                // 清空文本信息
                MyUtils.clearTextInTextView(tvType, tvSpec);
                break;

            // 扫描设备出问题时，只清空设备位置号
            case "QUERYEQPINFO":
                MyUtils.clearTextInTextView(tvEqpLocation);
                break;

            // 点击了领料类型出问题时，只清空规格里面的数据
            case "QUERYMATSPEC":
                // 清空物料规格列表内容
                if ( !specList.isEmpty() ) { specList.clear(); }
                // 清空相应文本
                MyUtils.clearTextInTextView(tvSpec);
                break;
        }
    }

    /**
     * 检查是否有相关信息未填写：批次、领料类型、规格、设备号、设备位置号和数量
     * @return boolean 是：有相关字段信息未填写，否：已经完成了信息的填写
     */
    private boolean checkPageViewHasEmptyValue() {

        return StringUtils.isEmpty(getText(etEqpID))
                || StringUtils.isEmpty(tvEqpLocation.getText())
                || StringUtils.isEmpty(getText(etLot))
                || StringUtils.isEmpty(tvType.getText())
                || StringUtils.isEmpty(tvSpec.getText())
                || StringUtils.isEmpty(getText(etQty));

    }

    /**
     * 添加领料单数据到数据集合中
     */
    private void addPickingEntityToAdapter() {
        if (checkPageViewHasEmptyValue()){
            showToast("填写未完成，请填写相关数据",false);
            return;
        }

        PickingEntity pickingEntity = new PickingEntity();
        pickingEntity.setLOTID(getText(etLot));
        pickingEntity.setSTEPNAME(tvStep.getText().toString());
        pickingEntity.setMATERIALTYPE(tvType.getText().toString());
        pickingEntity.setMATERIALSPEC(tvSpec.getText().toString());
        pickingEntity.setEQPID(getText(etEqpID));
        pickingEntity.setEQPLOCATION(tvEqpLocation.getText().toString());
        pickingEntity.setMAINQTY(getText(etQty));

        // 如果该批次，该物料规格有指定厂家的，添加进去领料单里，供后台显示
        if (StringUtils.isNotEmpty(materialMap.get(String.valueOf(tvSpec.getText())))) {
            pickingEntity.setRESERVED5(materialMap.get(String.valueOf(tvSpec.getText())));
        }

        // 胶水是否需要进行分支备注，提交给后台进行保存
        if (cbGlueNeedBranch.getVisibility() == View.VISIBLE && cbGlueNeedBranch.isChecked()) {
            pickingEntity.setRESERVED3(String.valueOf(cbGlueNeedBranch.getText()));
        }

        // 检查列表中是否有重复的数据
        if (mPickingDataAdapter.getData().size() > 0) {
            for (PickingEntity pickingEntityData :
                    mPickingDataAdapter.getData()) {
                if (StringUtils.equals(pickingEntityData.getEQPID(), pickingEntity.getEQPID())
                    && StringUtils.equals(pickingEntityData.getMATERIALSPEC(), pickingEntity.getMATERIALSPEC())) {
                    showConfirmDialog(String.format("设备号为%s，领料规格为%s的领料单已经存在于数据列表中，不需要重复添加", pickingEntityData.getEQPID(), pickingEntityData.getMATERIALSPEC()));
                    return;
                }
            }
        }

        mPickingDataAdapter.addData(0,pickingEntity);
    }

}